//
//  MyMessageViewModel.m
//  Yihubang
//
//  Created by xmy on 16/9/6.
//  Copyright © 2016年 jinghao. All rights reserved.
//

#import "MyMessageViewModel.h"
#import "MyMessageCell.h"
#import "MasterWebViewController.h"
@interface MyMessageViewModel()
@property (nonatomic, strong,readwrite)RACCommand *clearMessageCommend;
@property (nonatomic, strong)          RACCommand * goToGPSNaviVCCommand;
@property (nonatomic, strong)          NSMutableArray * sectionArr;;
@end

@implementation MyMessageViewModel
- (void)initialize
{
    [super initialize];
    //    [[self.requestRemoteDataCommand execute:nil] subscribeNext:^(id x) {
    //        NSLog(@"======111 ==== %@",x);
    //    }];
    @weakify(self);
    self.clearMessageCommend = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSArray *data) {
        @strongify(self)
        [[[HttpManagerCenter sharedHttpManager] clearMymessageresultClass:nil] subscribeNext:^(BaseModel *model){
            if(model.code ==200){
                [self.viewController hiddenHUDWithString:@"清空成功" error:NO];
                self.dataSource =@[];
                [self.mTableView reloadData];
            }else{
                [self.viewController hiddenHUDWithString:model.data error:NO];
            }
        }];

        return [RACSignal empty];
    }];
    self.goToGPSNaviVCCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath *indexPath) {
        @strongify(self)
        MyMessageCell *cell = (MyMessageCell*)[self.mTableView cellForRowAtIndexPath:indexPath];
        NSString * urlStr;
        if([cell.target_content containsString:@"emergency"]){
            NSRange range = [cell.target_content rangeOfString:@"id="];
            NSString * idStr =[cell.target_content substringFromIndex:range.location + range.length];
            urlStr =[NSString stringWithFormat:@"%@?emergency_id=%@",URL_AMapNaviWalkVC,idStr];
        }else{
            urlStr = cell.target_content;
        }
        if([cell.is_read integerValue] == 0){
            [self readThisInform:cell.reform_id index:indexPath];
        }
        [self.viewController pushViewControllerWithUrl:urlStr];
        [self.viewController.navigationController.navigationBar setHidden:YES];
        return [RACSignal empty];
    }];
    [RACObserve(self, messageType) subscribeNext:^(NSString *type) {
        [self first];
    }];
}
-(void)readThisInform:(NSString *)inform_id index:(NSIndexPath *)index{
    [[[HttpManagerCenter sharedHttpManager] readInformById:inform_id resultClass:nil] subscribeNext:^(BaseModel *model){
        if(model.code ==200){
        
        }else{
           
        }
    }];
    NSMutableDictionary * voiceDic = [NSMutableDictionary dictionaryWithDictionary:self.dataSource[index.section][index.row]];
    [voiceDic setObject:@"1" forKey:@"is_read"];
    NSMutableArray *dataSource = [[NSMutableArray alloc] initWithArray:self.dataSource];
    NSMutableArray *inform =[[NSMutableArray alloc] initWithArray:dataSource[index.section]];
    [inform replaceObjectAtIndex:index.row withObject:voiceDic];
    [dataSource replaceObjectAtIndex:index.section withObject:inform];
    self.dataSource = dataSource;
    [self.mTableView reloadData];
   
}

- (void)bindTableView:(UITableView *)tableView
{
    [super bindTableView:tableView];
    self.cellReuseIdentifier = @"MyMessageCell";
    [self.mTableView registerCellWithReuseIdentifier:@"MyMessageCell"];
    self.shouldMoreToRefresh = YES;
    self.shouldPullToRefresh = YES;
    self.pageSize = @(7);
}

- (RACSignal*)requestRemoteDataSignalWithPage:(NSUInteger)page
{
    RACSignal *fetchSignal = [self.httpService getMyMessage:page page_size:self.pageSize.integerValue withType:self.messageType resultClass:nil];
 
    //    return fetchSignal;
    @weakify(self);
    return [[[fetchSignal collect] doNext:^(id x) {
        NSLog(@"===== x %@",x);
        @strongify(self);
        if(self.mTableView.mj_footer.isRefreshing ){
            [self.mTableView.mj_footer endRefreshing];
        }
        if (self.mTableView.mj_header.isRefreshing) {
            [self.mTableView.mj_header endRefreshing];
        }
    }] map:^id(NSArray *responses) {
        NSLog(@"===== value  %@",responses);
        @strongify(self);
        self.mTableView.loadedImageName =@"wuMessage";
        self.mTableView.descriptionText=@"暂时没有任何消息";
        BaseModel *model = responses.firstObject;
        if (model.code==200) {
            NSMutableArray * array = [NSMutableArray arrayWithArray:model.data];
            if([self.curPage intValue] > 1){
                NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithArray:self.dataSource];
                [indexPaths addObjectsFromArray:array];
                self.dataSource = indexPaths;
            }else{
                self.dataSource = array;
            }
            if([self.dataSource count] >0){
                for (NSMutableArray * info in self.dataSource) {
                   [self.sectionArr addObject:info[0][@"format_time"]];
                }
            }
            [self.mTableView reloadData];
        }else{
            [self showRequestErrorMessage:model];
        }
        return [RACSignal empty];
        
    }];
}
- (void)configureCell:( MyMessageCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object
{
    [cell.clickTo_btn setHidden:[self.messageType isEqual:@"16"]];
    [cell.redBall_image setHidden:[object[@"is_read"] boolValue]];
    cell.target_content = object[@"target_content"];
    cell.is_read = object[@"is_read"];
    cell.reform_id = object[@"id"];
    cell.content_label.text =object[@"content"];
    cell.FormatTime_label.text = object [@"new_format_time"];
    cell.target_index = indexPath;
    cell.goToGPSNaviVCCommand = self.goToGPSNaviVCCommand;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.goToGPSNaviVCCommand execute:indexPath];
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * titleView = [UIView new];
    [titleView setBackgroundColor:[UIColor colorWithHex:0xF5F5F5]];
    titleView.frame = CGRectMake(0, 0, ScreenWidth, 44);
    UILabel * title = [UILabel new];
    title.text = self.sectionArr[section];
    title.font =[UIFont boldSystemFontOfSize:16.f];
    title.textColor = [UIColor colorWithHex:0x585858];
    [titleView addSubview:title];
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView).with.offset(13);
        make.centerY.equalTo(titleView);
    }];
    UILabel * line = [UILabel new];
    [line setBackgroundColor:[UIColor colorWithHex:0xEEEEEE]];
    [titleView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView).with.offset(0);
        make.right.equalTo(titleView).with.offset(0);
        make.bottom.equalTo(titleView).with.offset(0);
        make.height.equalTo(@0.5);
    }];

    return titleView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 44.f;
}
//要求委托方的编辑风格在表视图的一个特定的位置。
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCellEditingStyle result = UITableViewCellEditingStyleNone;//默认没有编辑风格
    result = UITableViewCellEditingStyleDelete;//设置编辑风格为删除风格
    return result;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{//请求数据源提交的插入或删除指定行接收者。
    if (editingStyle ==UITableViewCellEditingStyleDelete) {//如果编辑样式为删除样式
        @weakify(self);
        [[[HttpManagerCenter sharedHttpManager] deleteMessageByid:self.dataSource[0][indexPath.row][@"id"] resultClass:nil] subscribeNext:^(BaseModel *model){
            if(model.code ==200){
                @strongify(self);
                [self.dataSource[0] removeObjectAtIndex:indexPath.row];//移除数据源的数据
                [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];//移除tableView中的数据
            }
        }];
    }
}
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}
#pragma mark - lazyload

-(NSMutableArray *)sectionArr{
    if(!_sectionArr){
        _sectionArr = [NSMutableArray array];
    }
    return _sectionArr;
}
@end
